let cardSelection = module.exports;

let initiated = false;
let game;

let selectionCallback;
let cancelCallback;
let selectionMaxCount;
let selectionMinCount;

let selectedCards = [];

cardSelection.init = function (initConfig) { // { game: ... }
    if (initiated) return;
    game = initConfig.game;
    initiated = true;
};

// cb -> (selectedCards)
// cancelCb -> ()
cardSelection.start = function (filter, maxCount, minCount, cb, cancelCb) {
    selectionCallback = cb;
    cancelCallback = cancelCb;
    selectionMaxCount = maxCount;
    selectionMinCount = minCount;

    game.componentBroadcast('beforeCardChooseCandidate', this, filter);
};

cardSelection.select = function (card) {
    selectedCards.push(card);
    if (selectedCards.length == selectionMaxCount) {
        cardSelection.confirm();
    }
};

cardSelection.deselect = function (card) {
    for (let i = 0; i < selectedCards.length; ++i) {
        let item = selectedCards[i];
        if (item == card) {
            selectedCards.splice(i, 1);
            break;
        }
    }
};

function afterCardChoose() {
    game.componentBroadcast('afterCardChooseCandidate', this);
}

function clear() {
    selectedCards = [];
    selectionCallback = null;
    cancelCallback = null;
    selectionMaxCount = null;
    selectionMinCount = null;
}

cardSelection.confirm = function () {
    afterCardChoose();
    let __selectedCards = selectedCards;
    let __selectionCallback = selectionCallback;
    clear();
    __selectionCallback(__selectedCards);
};

cardSelection.cancel = function () {
    afterCardChoose();
    let __cancelCallback = cancelCallback;
    clear();
    __cancelCallback();
};
